package com.youkeda.yikao.web.control;


import com.google.code.kaptcha.Constants;
import com.youkeda.yikao.web.config.NeedLogin;
import com.youkeda.yikao.web.dao.ChenzikangUesrSystemMapper;
import com.youkeda.yikao.web.dataobject.ChenzikangUesrSystem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.server.Session;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttribute;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.util.DigestUtils;
import javax.servlet.http.HttpSession;

/**
 * 登录类，判断密码是否正确，并可以查询登录信息
 * <p>
 * 2019.8.26  chenzikang
 */
@Controller
public class LoginControl {

    @Autowired
    ChenzikangUesrSystemMapper chenzikangUesrSystemMapper;


    /**
     * 登录并验证密码是否正确
     */
    @RequestMapping(path = "/login")
    public ModelAndView search(@RequestParam("user") String user,
                               @RequestParam("pwd") String pwd,
                               HttpSession session) {
        ChenzikangUesrSystem chenzikangUesrSystem = chenzikangUesrSystemMapper.selectByPrimaryKey(user);

        String md5Password = DigestUtils.md5DigestAsHex(pwd.getBytes());

        //如果用户名为空，则跳回登录页
        if (chenzikangUesrSystem == null) {
            return new ModelAndView("redirect:login.html");
        }
        session.setAttribute("user", chenzikangUesrSystem);


        //如果密码正确则登录成功
        if (chenzikangUesrSystem.getPwd().equals(md5Password)) {
            return new ModelAndView("redirect:loginSuccess.html");
        }

        //如果密码不正确则，跳转回登录页
        return new ModelAndView("redirect:login.html");
    }


    /**
     * 查询登录信息
     */
    @RequestMapping(path = "/login/user")
    @ResponseBody
    @NeedLogin
    public ChenzikangUesrSystem getUser(@SessionAttribute("user") ChenzikangUesrSystem uesrSystem) {
        return uesrSystem;
    }


    /**
     * 退出登录
     */
    @RequestMapping(path = "/logout")
    @ResponseBody
    public String logout(HttpSession session) {
        session.removeAttribute("user");

        return "注销登录";
    }




}
